//
//  HICEmoticonTools.swift
//  vibo
//
//  Created by jht-seven on 16/7/5.
//  Copyright © 2016年 jht-seven. All rights reserved.
//

import UIKit

//显示的列数
let EmoticonMaxCol = 7
//显示的行数
let EmoticonMaxRow = 3
//每页显示的个数
let EmoticonMaxCount = EmoticonMaxCol * EmoticonMaxRow - 1

class HICEmoticonTools: NSObject {
    
    //全局访问点
    static let sharedTools: HICEmoticonTools = HICEmoticonTools()
    
    // 获得bundle
    lazy var emoticonBundle: NSBundle = {
        //获取bundle路径
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        //返回bundle
        return NSBundle(path: path)!
    }()
    
    //default 表情 一维数组
    lazy var defaultEmoticons: [HICEmoticon] = {
        return self.getEmoticons("default/")
    }()
    
    //emoji 表情 一维数组
    lazy var emojiEmoticons: [HICEmoticon] = {
        return self.getEmoticons("emoji/")
    }()
    
    //浪小花 表情 一维数组
    lazy var lxhEmoticons: [HICEmoticon] = {
        return self.getEmoticons("lxh/")
    }()
    
    // 表情三维数组
    lazy var allEmoticons:[[[HICEmoticon]]] = {
        return [
            self.getEmoticonsGroup(self.defaultEmoticons),
            self.getEmoticonsGroup(self.emojiEmoticons),
            self.getEmoticonsGroup(self.lxhEmoticons)]
    }()
    
    //读取plist文件中的数组转成模型一维数组
    func getEmoticons(fileName: String) -> [HICEmoticon]{
        //路径
        let file = emoticonBundle.pathForResource("\(fileName)info.plist", ofType: nil)!
        //plist 转数组
        let array = NSArray(contentsOfFile: file)!
        //创建一个可变的临时数组
        var tempArray: [HICEmoticon] = [HICEmoticon]()
        
        //遍历array
        for dic in array{
            let e = HICEmoticon(dict: dic as! [String: AnyObject])
            //获取路径
            e.path = "\(fileName)"
            //保存模型
            tempArray.append(e)
        }
        return tempArray
    }
    
    // 一维数组转二维数组
    func getEmoticonsGroup(emoticons: [HICEmoticon]) -> [[HICEmoticon]]{
        // 计算页数
        let pageCount = (emoticons.count  + EmoticonMaxCount - 1) / EmoticonMaxCount
        
        // 创建一个临时的可变的二维数组
        var tempArray:[[HICEmoticon]] = [[HICEmoticon]]()
        //遍历pageCount
        for i in 0..<pageCount {
            // 位置和长度
            let loc = EmoticonMaxCount * i
            var len = EmoticonMaxCount
            // 防止默认表情数组越界
            if loc + len > emoticons.count {
                len = emoticons.count - loc
            }
            // 截取范围
            let range = NSMakeRange(loc, len)
            // 数组的截取
            let arr = (emoticons as NSArray).subarrayWithRange(range) as![HICEmoticon]
            // 保存一维数组
            tempArray.append(arr)
        }
        // 返回二维数组
        return tempArray
    }
}
